package poswar.contribute.dao;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;

import poswar.contribute.model.Board;
import poswar.contribute.util.Config;
import poswar.contribute.util.FriendModeManager;

public class BoardDao {
	private static final Logger logger = Logger.getLogger(BoardDao.class);

	String XML_FILE = Config.getXmlPath() + "/board-data.xml";

	public void save(Board board) {
		// Create a File to marshal to
		try {
			FileWriter writer = new FileWriter(XML_FILE);

			// Marshal the person object
			Marshaller.marshal(board, writer);
			writer.close();
		} catch (Exception e) {
			// FIXME - Create exception
			throw new RuntimeException("Error saving board data", e);
		}
	}

	public Board load() {	
		if (logger.isDebugEnabled()) {
			logger.debug("reading file: " + XML_FILE);
		}
		
		FileReader reader = null;
		try {
			final FileReader innerReader = new FileReader(XML_FILE);
			reader = innerReader;
			Board board = FriendModeManager.callInFriendMode(new Callable<Board>() {		
				@Override
				public Board call() throws Exception {
					return (Board) Unmarshaller.unmarshal(Board.class, innerReader);
				}			
			});
			
			return board;
		} catch (Exception e) {
			logger.warn("Error loading board data", e);
			logger.info("No data was loaded. Starting a new board");
			
			Board board = new Board();
			return board;
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				logger.warn("Error loading board data", e);
			}
		}
	}
}
